import dingtalkoauth2_1_0, {
  GetAccessTokenRequest,
} from '@alicloud/dingtalk/dist/oauth2_1_0/client';
import Util from '@alicloud/tea-util';
import { getConfig } from '@libs/common/utils';

import { DingClientService } from './client.serivce';
const { DD } = getConfig();

export class DingAuthService extends DingClientService {
  constructor() {
    super();
  }

  private readonly client = new dingtalkoauth2_1_0(this.createClient());

  async getAccessToken() {
    const getAccessTokenRequest = new GetAccessTokenRequest({
      appKey: DD.DD_AppKey,
      appSecret: DD.DD_AppSecret,
    });

    try {
      const res = await this.client.getAccessToken(getAccessTokenRequest);
      if (res.body) {
        const expireIn = res.body.expireIn!;
        const accessToken = res.body.accessToken!;
        return { expireIn, accessToken };
      }

      throw new Error('获取 accessToken 为空: ' + JSON.stringify(res.body));
    } catch (err) {
      if (!Util.empty(err.code) && !Util.empty(err.message)) {
        // err 中含有 code 和 message 属性，可帮助开发定位问题
        throw new Error(err.message);
      } else {
        // 可能是网络问题，也可能是服务器端的问题
        throw new Error('获取 accessToken 失败: ' + JSON.stringify(err));
      }
    }
  }
}
